package com.bluesmart.mia;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;
import com.widget.BabyView;
import com.widget.HorizontalListView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class BabyChatActivity extends Fragment implements OnClickListener{
	JSONArray mArray = new JSONArray();
	HorizontalListViewAdapter mAdapter;
	boolean showWeight = true;
	
	int chartHeight = 0;
	int addHeight = 0;
	
	View mView;
	Context mContext;
	int showIndex = 1;
	
	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState)  
	{  
		mView = inflater.inflate(R.layout.activity_baby_chat, container, false);  
		mContext = getActivity();
		
		mView.findViewById(R.id.btn_left).setOnClickListener(this);
		mView.findViewById(R.id.btn_right).setOnClickListener(this);
		
		final HorizontalListView hlv = (HorizontalListView)mView.findViewById(R.id.hl); 
		mAdapter = new HorizontalListViewAdapter(mContext);
        hlv.setAdapter(mAdapter);  
        
        ((Button)mView.findViewById(R.id.btn_left)).setSelected(true);
        hlv.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				switch (event.getAction() & MotionEvent.ACTION_MASK)
				{
				case MotionEvent.ACTION_POINTER_DOWN:
	                oldDist = spacing(event);
	                break;
	                
				case MotionEvent.ACTION_POINTER_UP:
                    float newDist = spacing(event);
                    if(newDist > oldDist)
                    {
                    	if(showIndex < 2)
                    	{
                    		showIndex++;
                    		initData();
                    	}
                    }
                    else
                    {
                    	if(showIndex > 0)
                    	{
                    		showIndex--;
                    		initData();
                    	}
                    }
                    break; 
				}
				
				
				return false;
			}
        });
        
        sendChartHttpRequest(false);
        return mView;
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		sendChartHttpRequest(false);
	}
	
    float pointX = 0;
    float oldDist;
    @SuppressLint("FloatMath")
	private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }
	
	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.btn_left:
			showWeight = true;
			((Button)mView.findViewById(R.id.btn_left)).setTextColor(Color.parseColor("#e19a47"));
			((Button)mView.findViewById(R.id.btn_left)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a12, 0, 0, 0);
	        ((Button)mView.findViewById(R.id.btn_left)).setSelected(true);
	        
			((Button)mView.findViewById(R.id.btn_right)).setTextColor(Color.parseColor("#0fc0db"));
			((Button)mView.findViewById(R.id.btn_right)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a06, 0, 0, 0);
	        ((Button)mView.findViewById(R.id.btn_right)).setSelected(false);
	        
	        for(int i = R.id.y0; i <= R.id.y11; i++)
	        {
		        ((TextView)mView.findViewById(i)).setText((22 - 2*(i - R.id.y0)) + " -");
	        }
	        
	        mAdapter.notifyDataSetChanged();
			break;
			
		case R.id.btn_right:
			showWeight = false;
			((Button)mView.findViewById(R.id.btn_left)).setTextColor(Color.parseColor("#0fc0db"));
			((Button)mView.findViewById(R.id.btn_left)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a56, 0, 0, 0);
			 ((Button)mView.findViewById(R.id.btn_left)).setSelected(false);
			 
			((Button)mView.findViewById(R.id.btn_right)).setTextColor(Color.parseColor("#e19a47"));
			((Button)mView.findViewById(R.id.btn_right)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a57, 0, 0, 0);
			 ((Button)mView.findViewById(R.id.btn_right)).setSelected(true);
			 
			 for(int i = R.id.y0; i <= R.id.y11; i++)
			 {
				 ((TextView)mView.findViewById(i)).setText((95 - 5*(i - R.id.y0)) + " -");
			 }
			 mAdapter.notifyDataSetChanged();
			 break;
			
		case R.id.add:
			if(((Button)mView.findViewById(R.id.btn_left)).isSelected())
			{
				((ChatViewAtivity)mContext).startActivityForBaby(0);
			}
			else
			{
				((ChatViewAtivity)mContext).startActivityForBaby(1);
			}
			
			break;

		case R.id.btn_change:
			((MainPageActivity)mContext).changeView(R.id.btn0);
			break;
		}
	}

	Map pointMap = new HashMap();
	public void sendChartHttpRequest(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, show, false) {
			@Override
			public void onSuccess(String response) {
				chartHeight = mView.findViewById(R.id.hl).getHeight();
				addHeight = mView.findViewById(R.id.add_title).getHeight();
				
				mArray = JSON.parseArray(response);
				initData();
			}
		};
		
		JSONObject obj = ((DemoApp)mContext.getApplicationContext()).getSeletedBaby();

		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("babyid", obj.getString("babyid"));
		params.put("handType", "get");
	
		MgqRestClient.postBody(Constant.SERVER_URL + "/ViewMeasurementsData.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public void sendSwitchHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, true, false) {
			@Override
			public void onSuccess(String response) {
				sendChartHttpRequest(true);
			}
		};
		
		JSONObject obj = ((DemoApp)mContext.getApplicationContext()).getSeletedBaby();

		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("switchBabyid", obj.getString("babyid"));
		params.put("handType", "switch");
	
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	@SuppressWarnings("unchecked")
	void initData()
	{
		if(mArray.size() > 0)
		{
			JSONObject item = mArray.getJSONObject(mArray.size() - 1);
			
			double weight = item.getDoubleValue("weight_kg");
			double height = item.getDoubleValue("height_cm");
			if(((DemoApp) getActivity().getApplicationContext()).glbUnit == 1)
			{
				weight = 2.2*weight;
				height = height*0.39;

				((Button)mView.findViewById(R.id.btn_left)).setText(String.format("%.1f", weight) + "lb");
				((Button)mView.findViewById(R.id.btn_right)).setText(String.format("%.1f", height) + "inch");
			}
			else
			{
				((Button)mView.findViewById(R.id.btn_left)).setText(String.format("%.1f", weight) + "kg");
				((Button)mView.findViewById(R.id.btn_right)).setText(String.format("%.1f", height) + "cm");
			}

			JSONObject obj = ((DemoApp)mContext.getApplicationContext()).getSeletedBaby();
			Date date = Utils.ConverToDate(obj.getString("bday"), "yyyy-MM-dd");
			int age = (int) ((System.currentTimeMillis() - date.getTime())/(24*3600*1000));
			
			if(showIndex== 0)
			{
				int month = age/30;
				int week = (age - 30*month)/7;
				int day = age - 30*month - 7*week;
				
				((TextView)mView.findViewById(R.id.age)).setText(month + " " + mContext.getString(R.string.day_month) 
						+ ", " + week + " " + mContext.getString(R.string.week_age) 
						+ ", " + day + " " + mContext.getString(R.string.day_age));
				((TextView)mView.findViewById(R.id.x_title)).setText(mContext.getString(R.string.day_month));
			}
			else if(showIndex == 1)
			{
				int week = age/7;
				int day = age%7;
				
				((TextView)mView.findViewById(R.id.age)).setText(week + " " + mContext.getString(R.string.week_age) 
						+ ", " + day + " " + mContext.getString(R.string.day_age));
				((TextView)mView.findViewById(R.id.x_title)).setText(mContext.getString(R.string.week_age));
			}
			else
			{
				((TextView)mView.findViewById(R.id.age)).setText(age + " " + mContext.getString(R.string.day_age));
				((TextView)mView.findViewById(R.id.x_title)).setText(mContext.getString(R.string.day_age));
			}
		}
		
		final Handler handle = new Handler()
		{
			public void handleMessage(Message msg)
			{
				mAdapter.notifyDataSetChanged();
			}
		};
		
		new Thread(){
			public void run()
			{
				int daysLength = 7;
				if(showIndex == 0) daysLength = 30;
				else if(showIndex == 2) daysLength = 1;
				
				pointMap.clear();
				
				int i = 0;
				int index = 0;
				int count = mArray.size();
				ArrayList<JSONObject> array = new ArrayList<JSONObject>();
				
				while(i < count)
				{
					if(index > 0 && array.size() == 0) 
					{
						List<JSONObject> list = (List<JSONObject>)pointMap.get(String.valueOf(index - 1));
						if(list.size() > 0) array.add(list.get(list.size() - 1));
					}
					
					JSONObject item = mArray.getJSONObject(i);
					
					int day = item.getIntValue("age_in_days");
					if(day >= index*daysLength && day < (index + 1)*daysLength)
					{
						array.add(item);
						i++;
					}
					else
					{
						if(array.size() == 0)
						{
							JSONObject obj = new JSONObject();
							obj.put("height_cm", 41);
							obj.put("weight_kg", 0.5);
							array.add(obj);
						}
						
						pointMap.put(String.valueOf(index), array);
						index++;
						array = new ArrayList<JSONObject>();
					}
					
					if(i == count)
					{
						pointMap.put(String.valueOf(index), array);
						break;
					}
				}
				
				handle.sendEmptyMessage(0);
			}
		}.start();
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		
		if (resultCode == Activity.RESULT_OK) {
			if(requestCode == 10)
			{
				String value = data.getStringExtra("value");
				value = value.replace("kg", "");
				value = value.replace("lb", "");
				
				if(((DemoApp) getActivity().getApplicationContext()).glbUnit == 1)
				{
					double tmp = Double.valueOf(value);
					tmp = tmp/2.2;
					value = String.valueOf(tmp);
				}

				sendHttpUpdateRequest("weight",value);
				return;
			}
			
			if(requestCode == 11)
			{
				String value = data.getStringExtra("value");
				value = value.replace("cm", "");
				value = value.replace("inch", "");
				
				if(((DemoApp) getActivity().getApplicationContext()).glbUnit == 1)
				{
					double tmp = Double.valueOf(value);
					tmp = tmp/0.39;
					value = String.valueOf(tmp);
				}
				
				sendHttpUpdateRequest("height",value);
				return;
			}
		}
	}
	
	public void sendHttpUpdateRequest(String key,String value) {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					ToastUtil.showToastWithAlertPic(R.string.success);
					sendChartHttpRequest(false);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		
		JSONObject item = mArray.getJSONObject(mArray.size() - 1);
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
//		params.put("babyid", ((DemoApp)getApplicationContext()).getSeletedBaby().getString("babyid"));
		params.put("handType", "update");
		params.put("addDate", Utils.ConverToString(new Date(System.currentTimeMillis()), "yyyy-MM-dd"));
		params.put("height", item.getString("height_cm"));
		params.put("weight", item.getString("weight_kg"));
		params.put(key, value);
		//mia_un=liwentao@ijiebao.com&weight=6.0&pwd=D70C1E5D44DE8A9150EB91ECFF563578&handType=update&addDate=2015-09-06&height=60.0
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	class HorizontalListViewAdapter extends BaseAdapter{  
		private LayoutInflater mInflater;  
		public HorizontalListViewAdapter(Context con){  
	        mInflater = LayoutInflater.from(con);  
	    }  
		
	    @Override  
	    public int getCount() {  
			if(showIndex == 0) return 12;
			else if(showIndex == 2) return 365;
	    	
	        return 52;
	    }  
	    
	    @Override  
	    public Object getItem(int position) {  
	        return position;  
	    }  

	    private class ViewHolder {  
	        private TextView index ;  
	        private BabyView chart;
	        private TextView add ;  
	    }  
	    
	    @Override  
	    public long getItemId(int position) {  
	        return position;  
	    }  
	  
	    @Override  
	    public View getView(int position, View convertView, ViewGroup parent) {  
	    	ViewHolder vh = null;

	        if(true){
	        	vh = new ViewHolder();  
	            convertView = mInflater.inflate(R.layout.item_baby_info, null);  
	            vh.index = (TextView)convertView.findViewById(R.id.index);  
	            vh.chart = (BabyView)convertView.findViewById(R.id.chart); 
	            vh.add = (TextView)convertView.findViewById(R.id.add);  
	            convertView.setTag(vh);  
	        }
	        else{
	            vh = (ViewHolder)convertView.getTag();  
	        }
	        
	        if(chartHeight == 0)
	        {
	        	chartHeight = vh.chart.getHeight();
	        	addHeight = vh.add.getHeight();
	        }

	        vh.index.setText(String.valueOf(position + 1));
	        vh.chart.setPoint(position,pointMap,showWeight,showIndex);
	        
	        if(position == pointMap.size() - 1)
	        {
	        	vh.add.setVisibility(View.VISIBLE);

        		int yPos = 0;
        		if(showWeight) yPos = chartHeight - (int)(mArray.getJSONObject(mArray.size() - 1).getDoubleValue("weight_kg")*chartHeight/22);
        		else yPos = chartHeight - (int)((mArray.getJSONObject(mArray.size() - 1).getDoubleValue("height_cm") - 40)*chartHeight/55);

    	        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)vh.add.getLayoutParams();
    	        params.topMargin = yPos - addHeight;
    	        vh.add.setLayoutParams(params);
    	        vh.add.setOnClickListener(BabyChatActivity.this);
	        }
	        else
	        {
	        	vh.add.setVisibility(View.INVISIBLE);
	        }
	        		
	        return convertView;  
	    }  
	}  
}
